package netty.handler;

import com.alibaba.fastjson.JSONObject;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import rpc.CompletableRpcTask;

import java.util.Map;

/**
 * @author : zGame
 * @version V1.0
 * @Project: simple-rpc
 * @Package netty.handler
 * @Description: rpc接收netty返回内容进行处理
 * @date Date : 2022年02月28日 10:23
 */
public class RpcResponseHandler extends SimpleChannelInboundHandler<String> {
    
    private Map<String, CompletableRpcTask> rpcTaskMap;
    
    public RpcResponseHandler(Map<String, CompletableRpcTask> rpcTaskMap) {
        this.rpcTaskMap = rpcTaskMap;
    }
    
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        JSONObject SONObject = JSONObject.parseObject(s);
        String taskId = SONObject.getString("taskId");
        CompletableRpcTask rpcTask = rpcTaskMap.get(taskId);
        boolean complete = rpcTask.complete(SONObject.getString("result"));
        if(complete){
            rpcTask.getListener().taskFinish((byte)2,taskId);
        }else{
            rpcTask.getListener().taskFinish((byte)1,taskId);
        }
    }
    
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        rpcTaskMap.forEach((key, v) -> {
            v.cancel(true);
            v.getListener().taskFinish((byte)0,key);
        });
    }
}
